package org.micode.demo.biz.base;

import org.micode.common.helper.I18nMsgHelper;
import org.micode.demo.biz.service.BizSysConfigService;
import org.micode.common.exception.VerifyFailException;
import org.micode.common.validater.ValidateResult;
import org.micode.libs.cache.imagecode.IImageCodeCacheHandler;
import org.micode.libs.cache.imagecode.ImageCodeCache;
import org.micode.libs.cache.imagecode.ImageCodeProducer;
import org.micode.libs.cache.validater.ImageCodeValidater;
import org.micode.libs.dao.vo.ImageCodeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public abstract class BaseLoginService {

    @Autowired
    private IImageCodeCacheHandler imageCodeCacheHandler;

    @Autowired
    protected BizSysConfigService bizSysConfigService;

    public ImageCodeVO getImageCode(ImageCodeVO imageCodeDTO) {
        ImageCodeCache codeCache = ImageCodeProducer.newImageCode(
                bizSysConfigService.getImageCodeRetentionSeconds()
        );
        codeCache.setSessionId(imageCodeDTO.getSessionId());
        codeCache.setUuid(imageCodeDTO.getUuid());
        imageCodeCacheHandler.setByKey(codeCache.readCacheKey(), codeCache);

        imageCodeDTO.setImageCodeBase64(codeCache.getImageCodeBase64());
        return imageCodeDTO;
    }

    protected void validateImageCode(String uuid, String sessionId, String imageCode) {
        ValidateResult ret = ImageCodeValidater.validate(imageCode, sessionId, uuid);
        if (!ret.isValid()) {
            log.warn(I18nMsgHelper.get("valid.imageCode.verification-failed"));
            throw new VerifyFailException(ret.getInvalidMsg());
        }
    }

}
